package org.zjx.util;

import java.net.*;
import java.util.Enumeration;
import java.util.Optional;

public class IpUtil {

    /**
     * 获取本机局域网IP地址（非127.0.0.1）
     * @return 返回第一个有效的局域网IP地址
     */
    public static Optional<String> getLocalIp() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                // 跳过回环接口和未启用的接口
                if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                    continue;
                }

                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    // 只返回IPv4地址
                    if (address instanceof Inet4Address) {
                        return Optional.of(address.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return Optional.empty();
    }

    /**
     * 获取本机公网IP地址（通过外部服务查询）
     * @return 返回公网IP地址
     */
    public static Optional<String> getPublicIp() {
        try {
            // 使用多个公共服务进行查询，增加可靠性
            String[] services = {
                    "https://api.ipify.org",
                    "https://checkip.amazonaws.com",
                    "https://ipinfo.io/ip"
            };

            for (String service : services) {
                try {
                    URL url = new URL(service);
                    try (java.util.Scanner scanner = new java.util.Scanner(url.openStream())) {
                        String ip = scanner.useDelimiter("\\A").next().trim();
                        if (!ip.isEmpty()) {
                            return Optional.of(ip);
                        }
                    }
                } catch (Exception e) {
                    // 如果某个服务失败，尝试下一个
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Optional.empty();
    }

    /**
     * 获取主机名
     */
    public static Optional<String> getHostName() {
        try {
            return Optional.of(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }

    /**
     * 获取本机所有网络接口信息
     */
    public static void printNetworkInterfaces() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                System.out.println("Interface: " + networkInterface.getName() +
                        " (" + networkInterface.getDisplayName() + ")");

                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    System.out.println("  Address: " + address.getHostAddress() +
                            " (" + (address instanceof Inet4Address ? "IPv4" : "IPv6") + ")");
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println("局域网IP: " + getLocalIp().orElse("无法获取"));
        System.out.println("公网IP: " + getPublicIp().orElse("无法获取"));
        System.out.println("主机名: " + getHostName().orElse("无法获取"));
        System.out.println("\n所有网络接口信息:");
        printNetworkInterfaces();
    }
}